package com.cyy.view

import cn.hutool.core.io.FileUtil
import com.cyy.app.Styles
import com.cyy.model.Constants
import com.cyy.model.GmodelModel
import com.cyy.srv.GenSrv
import javafx.geometry.Orientation
import javafx.scene.control.MenuItem
import javafx.scene.control.TextArea
import javafx.scene.layout.Priority
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File

/**Enjoy模板练习
 * d:\Program\idea\jre64\bin\java.exe -jar build\libs\EnjoySqlite.jar
 */
class GEnjoy(val gmodel: GmodelModel, val genSrv: GenSrv) : View() {
    val engine = gmodel.engine.value
    var kv = mutableMapOf<String, String>()
    val ef = arrayOf(FileChooser.ExtensionFilter("choose db file", "*.db"))

    // Template String TextArea
    lateinit var ta: TextArea

    override val root = scrollpane(true, true) {
        form {
            vgrow = Priority.ALWAYS
            fieldset {
                field {
                    //                    combobox(gmodel.dbname,gmodel.dbs){
//                        selectionModel.selectedItemProperty().addListener { _, _, _ ->
//                            (if (!selectionModel.selectedItem.isNullOrEmpty()) {
////                                genSrv.prapare()
//                                genSrv.getAllTables()
//                            })
//                        }
//                    }
//                    combobox(gmodel.leftTable, gmodel.tables)
//                    combobox<Any>{
//                        items =  observableListOf(
//                                Constants.getSharedObjectMap(gmodel.engine.value).toString().trimStart('{').trimEnd('}') .split(",")
//                        )
////                        items =  observableListOf(
////                                Constants.getSharedObject(gmodel.engine.value)
////                        )
//                    }
                }
                field {
                    button("选择模板文件") {
                        //                        addClass(Styles.tackyButton)
                        action {
                            val efset = arrayOf(FileChooser.ExtensionFilter("选择模板文件", "*.*"))
                            val fnset = chooseFile("选择模板文件", efset, FileChooserMode.Single) {
                                // p初始目录为当前项目目录
                                initialDirectory = File(File("").canonicalPath)
                            }

                            if (fnset.isNotEmpty()) {
                                gmodel.engineTemplateFilePath.value = fnset.first().toString()
                                gmodel.tplString.value = FileUtil.readUtf8String(fnset.first())
                            }
                        }
                    }
                    textfield(gmodel.engineTemplateFilePath) {
                        promptText = "engine template file path"
                    }
                }
                separator(Orientation.HORIZONTAL)
                field {
                    button("渲染模板字符串") {
                        enableWhen(gmodel.tplString.isNotBlank())
                        action {
                            try {
                                gmodel.tplStringOut.value = engine.getTemplateByString(gmodel.tplString.value).renderToString(kv)
                            } catch (e: Exception) {
                                gmodel.tplStringOut.value = e.toString()
                            }
                        }
                    }
                    button("渲染选择的模板字符串") {
                        enableWhen(gmodel.tplString.isNotBlank())
                        action {
                            try {
                                val tplString = ta.selectedText
                                gmodel.tplStringOut.value = engine.getTemplateByString(tplString).renderToString(kv)
                            } catch (e: Exception) {
                                gmodel.tplStringOut.value = e.toString()
                            }
                        }
                    }

                    button("清空模板缓存") {
                        action {
                            engine.removeAllTemplateCache()
                        }
                    }
                    button("保存结果到文件") {
                        enableWhen(gmodel.tplStringOut.isNotBlank())
                        action {
                            try {
                                val efset = arrayOf(FileChooser.ExtensionFilter("save文件name", "*.*"))
                                val fnset = chooseFile("选择文件path", efset, FileChooserMode.Single) {
                                    initialDirectory = File(File("").canonicalPath)
                                }
                                if (fnset.isNotEmpty()) {
                                    FileUtil.writeUtf8String(gmodel.tplStringOut.value, fnset.first())
                                }

                            } catch (e: Exception) {
                                gmodel.tplStringOut.value = e.toString()
                            }
                        }
                    }


                }
            }

            hbox(10) {
                fieldset(labelPosition = Orientation.VERTICAL) {
                    field("Template String") {
                        ta = textarea(gmodel.tplString) {
                            prefHeight = 600.0
                            style {
                                fontSize = 16.px
                            }
                            required()
                            contextmenu {
                                item("渲染选中") {
                                    action {
                                        gmodel.tplStringOut.value = engine.getTemplateByString(ta.selectedText).renderToString(kv)
                                    }
                                }
                                item("渲染所有") {
                                    action {
                                        gmodel.tplStringOut.value = engine.getTemplateByString(ta.text).renderToString(kv)
                                    }
                                }
                                item("渲染当前行") {
                                    action {
                                        gmodel.tplStringOut.value = engine.getTemplateByString(ta.selectedText).renderToString(kv)
                                    }
                                }
                            }
                            text = """
                                #(1+2/3*4)
                                #(1>2)
                                #("abcdef".substring(0,3))
                                #set(arr=[1,2,3])
                                #(arr[1])
                                #set(menu='index')
                                #(menu=='index' ? 'current' : 'normal')
                                #(menu!="index" ? "current" : "normal")
                                #if(menu=='index')
                                    #(menu)
                                #end
                                #if(menu!='index')
                                    #(normal)
                                #else
                                    #(menu)
                                #end

                                #set(map={k1:123,"k2":"abc", "k3":gmodel})
                                #(map.k1)
                                #(map.k2)
                                #(map["k1"])
                                #(map["k2"])
                                #(map.get("k1"))
                                #({1:'自买', 2:'跟买'}.get(1))
                                #({1:'自买', 2:'跟买'}[2])

                                ### 与双问号符联合使用支持默认值
                                #({1:'自买', 2:'跟买'}.get(999) ?? '其它')

                                // 定义数组 array，并为元素赋默认值
                                #set(array = [123, "abc", true])
                                #set(array2 = [2123, "2abc", false])

                                // 获取下标为 1 的值，输出为: "abc"
                                #(array[1])

                                // 将下标为 1 的元素赋值为 false，并输出
                                #(array[1] = false, array[1])
                                ###set(array = [ 123, "abc", true, a && b || c, 1 + 2, obj.doIt(x) ])

                                #for(x : [1..10])
                                   #(x)
                                #end

                                // 对 Map 进行迭代
                                #for(x : map)
                                  #(x.key)
                                  #(x.value)
                                #end

                                // 对 List、数组、Set 这类结构进行迭代
                                #for(x : array)
                                   #(for.size)
                                   #(for.index)
                                   #(for.count)
                                   #(for.first)
                                   #(for.last)
                                   #(for.odd)
                                   #(for.even)

                                  #for(x : array2)
                                     #(for.outer)
                                     #(for.outer.index)
                                     #(for.index)
                                  #end
                                #end
                                #for(month=[1..12])
                                    #switch (month)
                                      #case (1, 3, 5, 7, 8, 10, 12)
                                        #(month) 月有 31 天
                                      #case (2)
                                        #(month) 月平年有28天，闰年有29天
                                      #default
                                        月份错误: #(month ?? "null")--#(month) 月平年有30天
                                    #end
                                #end
                                #(gmodel.baseResourcesPath ?? "gmodel is not exist")
                            """.trimIndent()
                        }
                    }
                }

                separator(Orientation.VERTICAL)
                fieldset("渲染结果") {
                    textarea(gmodel.tplStringOut) {
                        prefHeight = 600.0
                        required()
                        isWrapText = true
                        isEditable = false
                        style {
                            fontSize = 16.px
                        }
                    }
                }
            }
        }
    }
}
